package com.stylefeng.guns.modular.market.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.cash.service.IDetailsService;
import com.stylefeng.guns.modular.market.service.IMarketService;
import com.stylefeng.guns.modular.system.model.Details;
import com.stylefeng.guns.modular.system.model.Market;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * RMB市场专用收入/支出明细控制器
 *
 * @author fengshuonan
 * @Date 2018-07-27 16:37:13
 */
@Controller
@RequestMapping("/market")
public class MarketController extends BaseController {

    private String PREFIX = "/market/market/";

    @Autowired
    private IMarketService marketService;
    @Autowired
    private IDetailsService detailsService;

    /**
     * 跳转到RMB市场专用收入/支出明细首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "market.html";
    }

    /**
     * 跳转到添加RMB市场专用收入/支出明细
     */
    @RequestMapping("/market_add")
    public String marketAdd(Model model) {
        List<Details> list=detailsService.selectList(null);
        model.addAttribute("Details",list);
        return PREFIX + "market_add.html";
    }


    /**
     * 跳转到添加期初余额
     */
    @RequestMapping("/market_addBalance")
    public String market_addBalance(Model model) {
        return PREFIX + "market_addBalance.html";
    }

    /**
     * 跳转到导出页面
     */
    @RequestMapping("/market_export")
    public String marketExport() {
        return PREFIX + "market_export.html";
    }

    /**
     * 跳转到修改RMB市场专用收入/支出明细
     */
    @RequestMapping("/market_update/{marketId}")
    public String marketUpdate(@PathVariable Integer marketId, Model model) {
        Market market = marketService.selectById(marketId);
        List<Details> list=detailsService.selectList(null);
        model.addAttribute("item",market);
        model.addAttribute("Details",list);
        LogObjectHolder.me().set(market);
        return PREFIX + "market_edit.html";
    }

    /**
     * 获取RMB市场专用收入/支出明细列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@Platform String platform,@RequestParam(required = false)String beginDate,@RequestParam(required = false)String endDate)throws Exception {


        Page<Market> page = new PageFactory<Market>().defaultPage();
        EntityWrapper<Market> wrapper = new EntityWrapper<Market>();
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revdate", beginDate);
        }else{
            wrapper.ge("revdate", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revdate", endDate);
        }else{
            wrapper.le("revdate", DateUtil.today(1));
        }
        wrapper.eq("platform",platform);
        wrapper.orderBy("revdate",false);


        Page<Market> marketPage = marketService.selectPage(page,wrapper);
        latelyReord(marketPage,platform,beginDate);
        List<Market> marketList = new ArrayList<>();
        for (Market market : marketPage.getRecords()){
            double total = 0;
            if (market.getGroupRanking()!=null)
                total +=market.getGroupRanking();
            if (market.getQq()!=null)
                total +=market.getQq();
            if (market.getWcDraw()!=null)
                total +=market.getWcDraw();
            if (market.getOtherPromotion()!=null)
                total +=market.getOtherPromotion();
            market.setPayoutTatol(total);
            marketList.add(market);
        }
        marketPage.setRecords((List<Market>)new BaseModelWarpper(marketPage.getRecords(),Market.class).warpToObj());
        return marketList;
    }

  /**
   * 描述:最近一笔余额
   * 创建人: xiang
   * 日期: 2018/8/16
   * 时间: 15:53
   */
    public void latelyReord(Page<Market> object, String platform, String beginDate){
        //没有记录 默认查出最近一条
            Market market= marketService.selectOne( new  EntityWrapper<Market>()
                    .eq("platform",platform)
                    .lt("revdate", beginDate)
                    .orderBy("revdate DESC")
                    .orderBy("id desc")
                    .last("LIMIT 1")
            );
            if(market!=null){
                List<Market> list = object.getRecords();
                Market market1 = new Market();
                market1.setRemarks("上笔余额");
                market1.setBalance(market.getBalance());
                list.add(0,market1);
                object.setRecords(list);
            }
    }


    /**
     * 描述:统计市场专用表
     * 创建人: laoyu
     * 日期: 2018/8/9 0009
     * 时间: 上午 11:34
     */
    @RequestMapping(value = "total")
    @ResponseBody
    public Object total(@RequestParam(required = false)String platform,@RequestParam(required = false)String beginDate,@RequestParam(required = false)String endDate) {
        EntityWrapper<Market> wrapper = new EntityWrapper<Market>();
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("revdate", beginDate);
        }else{
            wrapper.ge("revdate", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("revdate", endDate);
        }else{
            wrapper.le("revdate", DateUtil.today(1));
        }
        if (StringUtils.isNotBlank(platform)&&Const.DEFAULT_PH.equals(ShiroKit.getUser().getDeptcode()))
            wrapper.eq("platform",platform);
        else
            wrapper.eq("platform",ShiroKit.getUser().getDeptcode());


        return marketService.total(wrapper);
    }
    /**
     * 新增RMB市场专用收入/支出明细
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Market market) {
        market.setPlatform(ShiroKit.getUser().getDeptcode());
        //设置当前余额
        double balance = marketService.searchLast(ShiroKit.getUser().getDeptcode());
        if (market.getIncome()!=null) {
            balance += market.getIncome();//收入
        }
        //支出
        if (market.getWcDraw()!=null) {
            balance -= market.getWcDraw();
        }
        if (market.getGroupRanking()!=null) {
            balance -= market.getGroupRanking();
        }
        if (market.getQq()!=null) {
            balance -= market.getQq();
        }
        if (market.getOtherPromotion()!=null) {
            balance -= market.getOtherPromotion();
        }
        market.setBalance(balance);
        market.setCreattime(new Date());
        marketService.insert(market);
        return SUCCESS_TIP;
    }


    /**
     *期初余额
     */
    @RequestMapping(value = "/addBalance")
    @ResponseBody
    public Object addBalance(Market market) {
        if(market.getRevdate()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请设置日期");
        }
        market.setRemarks("期数余额");
        market.setCreattime(new Date());
        marketService.insert(market);
        return SUCCESS_TIP;
    }

    /**
     * 删除RMB市场专用收入/支出明细
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer marketId) {

        //查询该笔订单
        Market market = marketService.selectById(marketId);
        if (!market.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"你无权删除该报表");
        marketService.deleteById(marketId);
        marketService.updateBalance(marketId,market);
        return SUCCESS_TIP;
    }

    /**
     * 修改RMB市场专用收入/支出明细
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Market market) {
        //查询当前报表
        Market oldMarket = marketService.selectById(market.getId());
        if (!oldMarket.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"你无权修改此条数据");

        marketService.update(oldMarket,market);
        return SUCCESS_TIP;
    }

    /**
     * RMB市场专用收入/支出明细详情
     */
    @RequestMapping(value = "/detail/{marketId}")
    @ResponseBody
    public Object detail(@PathVariable("marketId") Integer marketId) {
        return marketService.selectById(marketId);
    }

    /**
     * 描述:市场专用收入/支出明细
     * 创建人: laoyu
     * 日期: 2018/8/6 0006
     * 时间: 下午 1:40
     */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response,  @RequestParam(required = true) String beginDate, @RequestParam(required = true) String endDate) throws Exception {

        String platform = ShiroKit.getUser().getDeptcode();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        EntityWrapper<Market> wrapper  = new EntityWrapper<>();
        wrapper.eq("platform",platform);
        wrapper.ge("revdate",beginDate);
        wrapper.le("revdate",endDate);

        List<Market> marketList = marketService.selectList(wrapper);

        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/market.xlsx");

        modelMap.put(TemplateExcelConstants.FILE_NAME, platform.toUpperCase()+beginDate+"至"+endDate+"RMB市场专用收入/支出明细分类表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, marketService.load(marketList,beginDate,endDate,platform));
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }
}
